import router from './router'
import Performance from '@/tools/performance'
import { usePermissionStore } from "@/store/permission"
import { useUserStore } from "@/store/user"
import { Console } from 'console'

export function usePermission() {
    let end = null
    const whiteList = ['/login'] // 不重定向白名单
    router.beforeEach(async (to, from, next) => {

        console.log("Navigation guard!");
        
        //const { GenerateRoutes, routers } = usePermissionStore()
        const permissionStore = usePermissionStore();
        //const { GetUserInfo, token, roles, logOut } = useUserStore()
        //const { token,name,roles,logIn,logOut,GetUserInfo } = useUserStore();
        const userStore = useUserStore();
        //console.log("userStore:"+userStore.GetUserInfo);
        //console.log("permissionStore"+permissionStore);
  
        end = Performance.startExecute(`${from.path} => ${to.path} 路由耗时`) /// 路由性能监控
        var token = localStorage.getItem("jwt");
        var roles = localStorage.getItem("roles");
        if (token) {
            
            //console.log("have token");
            //console.log('token：',token);

            console.log("To Path-->"+to.path);
           /*  if (to.path === '/login') {
                next({ path: '/' })
            } else { */
            const hasRoles = roles && roles.length > 0;

            var routers= permissionStore.routers||[];
            console.log("router:"+routers);
            if (hasRoles && routers && routers.length > 0 ) {

                console.log("have roles");
                if (to.path !== from.path) { // 添加判断条件，只有当目标路径不等于当前路径时才进行重定向
                    next();
                    } else {
                    next(false); // 目标路径和当前路径相同，取消导航
                    }
            } else {
                try {

                    //debugger;
                    //const roles = JSON.parse(localStorage.getItem('roles'));//
                    const roles = await userStore.GetUserInfo();

                    console.log("have roles:have roles-->"+roles);
                    const accessRoutes = await permissionStore.GenerateRoutes(roles)
                    accessRoutes.forEach(item => {
                        router.addRoute(item)
                    })
                    next({ ...to, replace: true })
                } catch (error) {
                    await userStore.logOut()
                    console.error(error)
                    
                    next('/login')
                }
            }

            //}
        } else {
            
            console.log("have no token");
            
            if (whiteList.includes(to.path)) {
                next()
            } else {
                next('/login')
            }
        }

        setTimeout(() => {
            end()
        }, 0)
    })

    router.afterEach(() => { })
}
